package com.jilefojing.util;

import java.io.IOException;
import java.util.List;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jilefojing.beans.vo.UploadFile;
import com.jilefojing.qiniu.beans.enums.BucketEnum;
import com.jilefojing.qiniu.beans.enums.BucketEnum.BucketEnumExtral_SourceEnum;
import com.jilefojing.qiniu.beans.jilefojing2qiniu.request.ListURLRequest;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import com.qiniu.util.Json;
import com.qiniu.util.StringMap;

/**
 * @author 作者 jgshun
 * @version 创建时间：2016-7-15 下午1:02:46 类说明
 */
public class QiniuUtil {
	private static final Logger _LOGGER = LoggerFactory
			.getLogger(QiniuUtil.class);

	private static final String ACCESS_KEY = "Rcnd4s_HVEWr3G-FZjkL8QlwsUedj0reCG_Ugxi0";
	private static final String SECRET_KEY = "1ithKKbp_1mEXzdKPpu8YnF4n_nhBe7yduKRJbkx";

	/**
	 * 批量删除
	 * 
	 * @param targetBucket
	 *            删除的目标空间
	 * @param keysOfTargetBucket
	 *            删除的key
	 * @throws QiniuException
	 */
	public static void delete(BucketEnum targetBucket,
			List<String> keysOfTargetBucket) throws QiniuException {
		// 创建Batch类型的operations对象
		BucketManager.Batch operations = new BucketManager.Batch();
		for (String _KeyOfFromBucket : keysOfTargetBucket) {
			operations.delete(targetBucket.getValue(), _KeyOfFromBucket);
		}
		// 调用批量操作的batch方法
		Response res = createBucketManager().batch(operations);
		_LOGGER.info("批量删除结束:" + res);
	}

	/**
	 * 批量移动
	 * 
	 * @param toBucket
	 *            移动目的
	 * @param fromBucket
	 *            移动源
	 * @param keysOfFromBucket
	 *            移动源中的key列表
	 * @throws QiniuException
	 */
	public static void move(BucketEnum toBucket, BucketEnum fromBucket,
			List<String> keysOfFromBucket) throws QiniuException {
		// 创建Batch类型的operations对象
		BucketManager.Batch operations = new BucketManager.Batch();
		for (String _KeyOfFromBucket : keysOfFromBucket) {
			operations.move(fromBucket.getValue(), _KeyOfFromBucket,
					toBucket.getValue(), _KeyOfFromBucket);
		}
		// 调用批量操作的batch方法
		Response res = createBucketManager().batch(operations);
		_LOGGER.info("批量转移结束:" + res);
	}

	public static FileListing getFileListing(ListURLRequest listURLRequest)
			throws QiniuException {
		FileListing fileListing = createBucketManager().listFiles(
				listURLRequest.getBucket().getValue(),
				listURLRequest.getPrefix(), listURLRequest.getMarker(),
				listURLRequest.getLimit(), listURLRequest.getDelimiter());
		// FileInfo[] items = fileListing.items;
		// for(FileInfo fileInfo:items){
		// System.out.println(fileInfo.key);
		// }
		return fileListing;
	}

	/**
	 * 上传到七牛，返回外部链接
	 * 
	 * @param bytes
	 * @param bucket
	 * @param extral_SourceEnum
	 * @param suffix
	 * @return
	 */
	public static String upload(UploadFile uploadFile, BucketEnum bucket,
			BucketEnumExtral_SourceEnum extral_SourceEnum) {
		return upload(uploadFile.getBytes(), bucket,
				createKey(bucket, extral_SourceEnum, uploadFile));
	}

	/**
	 * 上传到七牛，返回外部链接
	 * 
	 * @param bytes
	 * @param bucket
	 * @param key
	 * @return
	 */
	public static String upload(byte[] bytes, BucketEnum bucket, String key) {
		UploadManager uploadManager = new UploadManager();
		String url = null;

		// 获取token
		String token = getToken(bucket);
		// 上传到七牛
		try {
			Response r = uploadManager.put(bytes, key, token);
			if (r.statusCode == 200) {
				StringMap json = Json.decode(r.bodyString());
				url = (String) json.get("key");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return url;
	}

	/**
	 * @param bucket
	 * @param extral_SourceEnum
	 * @param suffix
	 * @return
	 */
	public static String createKey(BucketEnum bucket,
			BucketEnumExtral_SourceEnum extral_SourceEnum, UploadFile uploadFile) {
		StringBuilder keyBud = new StringBuilder();
		if (extral_SourceEnum != null) {
			keyBud.append(extral_SourceEnum.getValue()).append("/");
		} else {
			if (bucket == BucketEnum.VIDEO) {
				keyBud.append("video").append("/");
			} else if (bucket == BucketEnum.AUDIO) {
				keyBud.append("audio").append("/");
			}
		}
		keyBud.append(new DateTime().toString("yyyyMMdd")).append("/");
		if (Detect.notEmpty(uploadFile.getName())) {
			keyBud.append(uploadFile.getName());
		} else {
			keyBud.append(new DateTime().toString("HHmmssSSS")).append(".")
					.append(uploadFile.getSuffix());
		}

		return keyBud.toString();
	}

	public static BucketManager createBucketManager() {
		// 实例化一个BucketManager对象
		BucketManager bucketManager = new BucketManager(createAuth());
		return bucketManager;
	}

	public static Auth createAuth() {
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		return auth;
	}

	public static String getToken(BucketEnum bucket) {
		String token = null;
		if (bucket == BucketEnum.VIDEO) {
			StringMap policy = new StringMap().put("insertOnly", 1).put(
					"mimeLimit", "application/x-mpegurl;video/*");
			token = createAuth().uploadToken(bucket.getValue(), null, 43200,
					policy);
		} else {
			token = createAuth().uploadToken(bucket.getValue());
		}

		// 覆盖上传，题目相关图片时用到，String token = auth.uploadToken(bucket, key);
		return token;
	}

	public static String getImagesDomain() {
		return "http://oe2fpvujn.bkt.clouddn.com/";
	}

	public static String getVideosDomain() {
		return "http://oe2f2bgkz.bkt.clouddn.com/";
	}

	public static String getAudiosDomain() {
		return "http://oe2fqxebf.bkt.clouddn.com/";
	}

	public static String getDomainByBucket(BucketEnum bucket) {
		if (bucket == BucketEnum.VIDEO) {
			return getVideosDomain();
		} else if (bucket == BucketEnum.AUDIO) {
			return getAudiosDomain();
		} else if (bucket == BucketEnum.IMG) {
			return getImagesDomain();
		}
		return null;
	}
}
